/**
 * Copyright 2018-2019 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.fos.bos;

import com.baidubce.BceClientConfiguration;
import com.baidubce.auth.BceCredentials;
import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.sts.StsClient;
import com.baidubce.services.sts.model.GetSessionTokenRequest;
import com.baidubce.services.sts.model.GetSessionTokenResponse;
import com.jianggujin.fos.JSecurityToken;
import com.jianggujin.fos.JSecurityTokenService;
import com.jianggujin.fos.bos.JBOSConfiguration.JBOSSessionTokenConfiguration;

import lombok.NonNull;

/**
 * @author jianggujin
 *
 */
public class JBOSSecurityTokenService implements JSecurityTokenService {
    // 目前使用STS配置client时，无论对应BOS服务的endpoint在哪里，endpoint都需配置为http://sts.bj.baidubce.com。
    private final static String STS_ENDPOINT = "http://sts.bj.baidubce.com";
    private StsClient client = null;
    private GetSessionTokenRequest request = null;

    public JBOSSecurityTokenService(@NonNull JBOSConfiguration configuration) {
        BceCredentials credentials = new DefaultBceCredentials(configuration.getAccessKeyId(),
                configuration.getSecretAccessKey());
        this.client = new StsClient(
                new BceClientConfiguration().withEndpoint(STS_ENDPOINT).withCredentials(credentials));
        request = new GetSessionTokenRequest();
        JBOSSessionTokenConfiguration sessionTokenConfiguration = configuration.getSessionTokenConfiguration();
        request = new GetSessionTokenRequest();
        if (sessionTokenConfiguration.getAcl() != null) {
            request.setAcl(sessionTokenConfiguration.getAcl());
        }
        if (sessionTokenConfiguration.getDurationSeconds() != null) {
            request.setDurationSeconds(sessionTokenConfiguration.getDurationSeconds());
        }
    }

    @Override
    public JSecurityToken getSecurityToken() {
        GetSessionTokenResponse response = client.getSessionToken(request);
        return new JSecurityToken(response.getAccessKeyId(), response.getSecretAccessKey(), response.getSessionToken(),
                response.getExpiration().getTime());
    }

    @Override
    public void destory() {
        if (client != null) {
            client.shutdown();
        }
    }
}
